package com.apop.common.exception;

import com.apop.common.model.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @ClassName GlobalExceptionHandler
 * @Author Jiayi Zheng
 * @Date 2021/11/11 19:57
 * @Description: 全局异常处理
 * @Version V1.0
 */
@ControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    /**
     * 处理自定义的业务异常
     * @param req
     * @param e
     * @return
     */
    @ExceptionHandler(value = BizException.class)
    @ResponseBody
    public Result bizExceptionHandler(HttpServletRequest req, BizException e){
        log.error("发生业务异常！{} 原因是：{}",e.getErrorCode() ,e.getErrorMsg());

        if ( e.getErrorCode().equals("E501")){
            return Result.fail(501,e.getErrorMsg());
        }

        return Result.fail(500,e.getErrorCode()+" "+e.getErrorMsg());
    }

    /**
     * 处理空指针的异常
     * @param req
     * @param e
     * @return
     */
    @ExceptionHandler(value =NullPointerException.class)
    @ResponseBody
    public Result exceptionHandler(HttpServletRequest req, NullPointerException e){
        log.error("发生空指针异常！原因是:",e);
        return Result.fail(500,"发生空指针异常！原因是:"+e.getMessage());
    }


    /**
     * 处理其他异常
     * @param req
     * @param e
     * @return
     */
    @ExceptionHandler(value =Exception.class)
    @ResponseBody
    public Result exceptionHandler(HttpServletRequest req, Exception e){
        log.error("未知异常！原因是:",e);
        return Result.fail(500,"未知异常！原因是:"+e);
    }

    /**
     * 接口参数校验异常
     * @param req
     * @param e
     * @return
     */
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    @ResponseBody
    public Result validExceptionHandler(HttpServletRequest req, MethodArgumentNotValidException e){
        log.error("参数校验异常！原因是:",e);
        BindingResult bindResult = e.getBindingResult();
        StringBuilder sb = new StringBuilder();
        List<ObjectError> allError = bindResult.getAllErrors();
        for (ObjectError error : allError) {
            sb.append(error.getDefaultMessage()).append(",");
        }

        return Result.fail(500,sb.toString().substring(0,sb.length()-1));
    }


}
